package com.dly.blog.controller;

import com.dly.blog.annotation.IgnoreAccess;
import com.dly.blog.annotation.OpLog;
import com.dly.blog.domian.ro.*;
import com.dly.blog.domian.vo.AdminLoginVO;
import com.dly.blog.domian.vo.LoginVO;
import com.dly.blog.msg.R;
import com.dly.blog.service.AuthenticationService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.validation.Valid;
import lombok.RequiredArgsConstructor;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.io.IOException;

@RestController
@RequestMapping
@RequiredArgsConstructor
@Tag(name = "权限模块")
public class AuthenticationController extends BaseController {

    private final AuthenticationService service;


    @PostMapping("/auth/admin_login")
    @OpLog(value = "后台登入接口", hasAuth = false)
    @Operation(summary = "后台登入接口")
    @IgnoreAccess
    public ResponseEntity<R<AdminLoginVO>> adminLogin(@RequestBody @Valid AdminRO adminRO, BindingResult br){
        return operate(()-> this.successDate(service.adminLogin(adminRO)), br);
    }

    @PostMapping("/auth/wxLogin")
    @OpLog(value = "微信登入操作", hasAuth = false)
    @Operation(summary = "微信登入接口")
    @IgnoreAccess
    public ResponseEntity<R<LoginVO>> wxAuth(@RequestBody @Valid WxLoginRO loginRO, BindingResult br){
        return operate(()-> this.successDate(service.wxLogin(loginRO)), br);
    }

    @PostMapping("/auth/login")
    @OpLog(value = "登入操作", hasAuth = false)
    @Operation(summary = "登入接口")
    @IgnoreAccess
    public ResponseEntity<R<LoginVO>> authenticate(
            @Validated @RequestBody LoginRO loginRO
    ) {
        return operate(() -> this.successDate(service.authenticate(loginRO)));
    }

    @PostMapping("/auth/register")
    @Operation(summary = "注册接口")
    @IgnoreAccess
    public ResponseEntity<R<LoginVO>> register(
            @RequestBody UserRegisterRO userRegisterRO
    ) {
        return operate(() -> this.successDate(service.register(userRegisterRO)));
    }

    @PostMapping("/auth/refreshToken")
    @Operation(summary = "token刷新接口")
    @IgnoreAccess
    public ResponseEntity<R<LoginVO>> refreshToken(
        String refreshToken
    ){
        return operate(()-> this.successDate(service.refreshToken(refreshToken)));
    }

    @PostMapping("/auth/logout")
    @Operation(summary = "退出接口")
    public ResponseEntity<R<Void>> logout(){
        service.logout();
        return operate(this::success);
    }
}
